package org.fle4y.app.server.database;

import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;
import java.sql.SQLException;

/**
 * author : xiehui<br>
 * company : northking <br>
 * Create at: 2012-6-26<br>
 * @version : 1.0<br>
 * mailto:flexie@foxmail.com<br>
 *  Description :
 */
public class Node {
	int iBalance;
	int iLeft, iRight, iParent;
	Node nLeft, nRight, nParent;
	private int iId;
	Node nNext;
	Row rData;

	public Node(Row r, DataInput in, int id) throws IOException, SQLException {
		iId = id;
		rData = r;
		iBalance = in.readInt();
		iLeft = in.readInt();
		iRight = in.readInt();
		iParent = in.readInt();

	}

	public Node(Row r, int id) {
		iId = id;
		rData = r;
	}

	public void delete() {
		iBalance = -2;
		nLeft = nRight = nParent = null;
		iLeft = iRight = iParent = 0;
	}

	public int getKey() {
		return rData.iPos;
	}

	public Node getLeft() throws SQLException {

		if (iLeft == 0) {
			return nLeft;
		}
		return rData.getNode(iLeft, iId);
	}

	public void setLeft(Node n) throws SQLException {

		rData.changed();

		if (n == null) {
			iLeft = 0;
			nLeft = null;
		} else if (n.rData.iPos != 0) {
			iLeft = n.rData.iPos;
		} else {
			nLeft = n;
		}
	}

	public Node getRight() throws SQLException {

		if (iRight == 0) {
			return nRight;
		}
		return rData.getNode(iRight, iId);
	}

	public void setRight(Node n) throws SQLException {

		rData.changed();
		if (n == null) {
			iRight = 0;
			nRight = null;
		} else if (n.rData.iPos != 0) {
			iRight = n.rData.iPos;
		} else {
			nRight = n;
		}
	}

	public Node getParent() throws SQLException {
		
		if (iParent == 0) {
			return nParent;
		}
		return rData.getNode(iParent, iId);
	}

	public void setParent(Node n) throws SQLException {

		rData.changed();

		if (n == null) {
			iParent = 0;
			nParent = null;
		} else if (n.rData.iPos != 0) {
			iParent = n.rData.iPos;
		} else {
			nParent = n;
		}
	}

	public int getBalance() throws SQLException {

		return iBalance;
	}

	public void setBalance(int b) throws SQLException {

		if (iBalance != b) {
			rData.changed();
			iBalance = b;
		}
	}

	public Object[] getData() throws SQLException {

		return rData.getData();
	}

	public boolean equals(Node n) throws SQLException {
		return n == this;
	}

	public void write(DataOutput out) throws IOException, SQLException {
		out.writeInt(iBalance);
		out.writeInt(iLeft);
		out.writeInt(iRight);
		out.writeInt(iParent);
		if (nNext != null) {
			nNext.write(out);
		}
	}
}
